import React, {
  useEffect, useMemo, useRef, useState, forwardRef,
} from 'react'
import {
  Button, Form, Input, message, Modal, notification,
} from 'antd'
import $ from 'jquery'
import Https, { getProjectId } from '@/utils/https'
import { getOSInfo } from './api'

const OSSyncComponentModal = (props) => {
  const [connectorId, setConnectorId] = useState('')
  const [osEndPoint, setOsEndPoint] = useState('')
  const [connectorVersion, setConnectorVersion] = useState('')
  const [form] = Form.useForm()
  const {
    visible, onClose, label, jobtype, jobid,
  } = props

  useEffect(() => {
    if (process.env.APP_ENV === 'os') {
      getOSInfo().then(
        (res) => {
          setConnectorId(res.connectorId)
          setConnectorVersion(res.connectorVersion)
          setOsEndPoint(res.osEndPoint)
        },
      )
    }
  }, [])

  useEffect(() => {
    if (visible) {
      form.setFieldsValue({ label })
    }
  }, [visible])

  const closeModal = () => {
    form.resetFields()
    onClose && onClose()
  }

  const onConfirm = () => {
    form.validateFields().then(values => {
      const data = {
        componentId: connectorId,
        params: [
          {
            key: 'hufu_endpoint',
            value: osEndPoint,
          },
          {
            key: 'jobtype',
            value: jobtype,
          },
          {
            key: 'workspaceid',
            value: `${getProjectId() || sessionStorage.getItem('projectId')}`,
          },
          {
            key: 'jobid',
            value: String(jobid),
          },
        ],
        docker: {
          dockerRepo: `hufu-connect:${connectorVersion}`,
        },
        ...values,
       }
      // console.log(data)
      // Https.post(`${window.location.origin}/app/graph/nodes`, data, { needCode: true }).then(
      //   (res) => {
      //     console.log(res)
      //     if (res.success) {
      //       message.success('同步成功')
      //     } else {
      //       notification.error({
      //         message: '同步失败',
      //         description: res.message,
      //       })
      //     }
      //   },
      //   (error) => {
      //     console.log(error)
      //   },
      // )
      // const xhr = new XMLHttpRequest()
      // xhr.open('POST', `${window.location.origin}/app/graph/nodes`, true)
      // xhr.setRequestHeader('Content-Type', 'application/json')
      // xhr.onreadystatechange = function () {
      //   if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
      //     console.log(xhr.responseText)
      //   }
      // }
      // xhr.send(JSON.stringify(data))
      const ajaxobj = $.ajax({
        url: `${window.location.origin}/app/graph/nodes`,
        type: 'post',
        data: JSON.stringify(data),
        contentType: 'application/json',
        processData: false,
        cache: false,
        xhrFields: {
          withCredentials: true,
        },
        success: (res) => {
          if (res.success) {
            message.success('同步成功')
            closeModal()
          } else {
            notification.error({
              message: '同步失败',
              description: res.message,
            })
          }
        },
        error: (err) => {
          console.log(err)
        },
      })
    })
  }

  return (
    <Modal
      title="同步至系统工程"
      cancelText="取消"
      okText="确认"
      visible={visible}
      onOk={onConfirm}
      onCancel={closeModal}
    >
      <Form
        form={form}
        labelCol={{ span: 7 }}
        wrapperCol={{ span: 17 }}
        autoComplete="off"
      >
        <Form.Item
          label="节点名称"
          name="label"
          rules={[
            { required: true, message: '请输入节点名称' },
          ]}
        >
          <Input placeholder="请输入节点名称" />
        </Form.Item>
        <Form.Item
          label="系统工程项目ID"
          name="id"
          rules={[
            { required: true, message: '请输入系统工程项目ID' },
          ]}
        >
          <Input placeholder="请输入系统工程项目ID" />
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default forwardRef((props, ref) => <OSSyncComponentModal {...props} refInstance={ref} />)
